package eclipse.util;
import eclipse.lib.scripting.*;
/**
 *  A basic thread interface that has CPU limitations.
 * Interval represents how many ms delay between executions
 * setRunStatus(false); will kill the thread
 * setEnabled(true); is required for running.
 */
public abstract class ThreadedTimer extends Thread
{
	private long 	Interval	= 1000;
	private boolean Enabled		= false;
	private boolean isRunning 	= false;
	private boolean Scripted 	= false;
	private String 	Script 		= "";
	/**
	 * Sets how frequent the thread is executed
	 * @param lInterval Frequency in milliseconds
	 */
	public void setInterval(long lInterval)
	{
		Interval = lInterval;
	}
	/**
	 * Returns the frequency of execution
	 * @return
	 */
	public long getInterval()
	{
		return Interval;
	}
	/**
	 * Enables the execution of the Related code
	 * @param bEnabled
	 */
	public void setEnabled(boolean bEnabled)
	{
		Enabled = bEnabled;
	}
	/**
	 * Returns if the Timer is enabled.
	 */
	public boolean getEnabled()
	{
		return Enabled;
	}
	/**
	 * Sets the run status of the Thread.
	 * false = Shuts down the thread
	 */
	public void setRunStatus(boolean bStatus)
	{
		isRunning = bStatus;
	}
	/**
	 * Returns the run status of the Thread.
	 * Same as isAlive();
	 */
	public boolean getRunStatus()
	{
		return isRunning;
	}
	/** 
	 * Sets whether the thread will execute a script
	 */
	public void setScripted(boolean bScripted)
	{
		Scripted = bScripted;
	}
	/**
	 * Returns whether the thread executes a script.
	 */
	public boolean getScripted()
	{
		return Scripted;
	}
	/**
	 * Sets the thread to execute a script.
	 * @param sScript The script the thread will execute
	 */
	public void setScript(String sScript)
	{
		Script = sScript;	
	}
	/**
	 * Returns the script that the thread executes
	 * @return
	 */
	public String getScript()
	{
		return Script;
	}
	/**
	 * Creates a ThreadedTimer object
	 */
	public ThreadedTimer()
	{
		isRunning 	= true;
	}
	/**
	 * Creates a ThreadedTimer object
	 * @param iInterval Frequency of execution
	 * @param Script Script executed
	 */
	public ThreadedTimer(int iInterval, String Script)
	{
		Interval	= iInterval;
		isRunning 	= true;
		Scripted 	= true;
	}
	/**
	 * Creates a ThreadedTimer object
	 * @param iInterval Frequency of execution
	 */
	public ThreadedTimer(int iInterval)
	{
		Interval 	= iInterval;
		isRunning 	= true;		
	}
	public void run()
	{
		while(isRunning)
		{
			if(Enabled)
			{
				tick();
				if(Scripted)
				{
					JScript.run(Script);
				}
			}
			Sleep(Interval);
		}
		System.out.println("Ending Thread: " + getName());
	}
	/**
	 * Pauses the thread
	 * @param ms Miliseconds for pause
	 */
	public void Sleep(long ms)
	{
		try {
			sleep(ms);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * Hardcoded to run as timed.	 
	 */
	public abstract void tick();
}
